package cn.edu.sdjzu.xg23.kcsj01_backend.service;

import cn.edu.sdjzu.xg23.kcsj01_backend.entity.Journal;
import cn.edu.sdjzu.xg23.kcsj01_backend.entity.JournalImpact;
import cn.edu.sdjzu.xg23.kcsj01_backend.mapper.JournalMapper;
import cn.edu.sdjzu.xg23.kcsj01_backend.utils.SnowflakeIdGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
public class JournalService {

    @Autowired
    private JournalMapper journalMapper;
    @Autowired
    private SnowflakeIdGenerator snowflakeIdGenerator;
    @Autowired
    private JournalImpactService journalImpactService;

    public PageInfo<Journal> get(int pageNum, int pageSize, Journal journal) {
        PageHelper.startPage(pageNum, pageSize);
        List<Journal> journalList = journalMapper.get(journal);
        return PageInfo.of(journalList);
    }

    @Transactional
    public String save(Journal journal) {
        if( journal.getId() == null){
            Long id = snowflakeIdGenerator.generateId();
            journal.setId(id);
        }

        JournalImpact journalImpact = journal.getJournalImpact();

        if( journalImpact.getId() == null){
            journalImpactService.save(journalImpact);
        }
        if (journalMapper.save(journal)) {
            return "保存成功";
        }
        return "保存失败";
    }

    public String update(Journal journal) {
        if (journalMapper.update(journal)) {
            return "修改成功";
        }
        System.out.println("修改失败");
        return "修改失败";
    }

    public String delete(long id) {
        if (journalMapper.delete(id)) {
            return "删除成功";
        }
        return "删除失败";
    }
}
